function ObjectBag(sizeX, sizeY) {"use strict";
	var nodeDistanceFunction, nodeDimensionAttributes, i;
	//
	// Initialize kdtree
	 nodeDistanceFunction = function(obj1, obj2){"use strict";
	  return Math.sqrt(Math.pow(obj1.x - obj2.x, 2) +  Math.pow(obj1.y - obj2.y, 2));
	};
	nodeDimensionAttributes=["x","y"];
	this.kdtree=new KDTree(null,nodeDistanceFunction,nodeDimensionAttributes);
	//
	// Initialize busy cells map
	//
	var busyCellsMap = new Array(sizeX);
	for (i = 0; i < busyCellsMap.length; i=i+1) {
		busyCellsMap[i] = new Array(sizeY);
		//
		var j = sizeY;
		while (j--) {
			busyCellsMap[i][j] = 0;
		}
	}
	this.busyCellsMap = busyCellsMap;
}

ObjectBag.prototype.objects = [];

// Finds object closest to given coordinates
ObjectBag.prototype.findClosestObject = function(xo, yo) {"use strict";
	// Convert from orthografic coordinates to isometric ones
	var tx = CoordinatesUtil.getTileX(xo,yo);
	var ty = CoordinatesUtil.getTileY(xo,yo);
	//
	var list=this.kdtree.findNearest( {x:tx,y:ty}, 1, 4);
	if (list==null || list.length<1){
		return null;
	} 
	return list[0][0];
};

// adds object to the bag
ObjectBag.prototype.add = function(obj) {"use strict";
	//
	// Add object to object bag
	this.objects.push(obj);
	//
	// Add object to kdtree
	this.kdtree.insert(obj);
	//
	// Add object to busyCellsMap
	var i,j;
	for (i=0;i<obj.getSizeBusyX();i+=1){
		for (j=0;j<obj.getSizeBusyY();j+=1){
			this.busyCellsMap[obj.getInitialBusyX()+i][obj.getInitialBusyY()+j]+=1;
		}
	}
}

// updates object position
ObjectBag.prototype.updateNodeCoordinates = function(obj, point) {"use strict";
	//
	// Remove object from busyCellsMap using old coordinates
	var i,j;
	for (i=0;i<obj.getSizeBusyX();i+=1){
		for (j=0;j<obj.getSizeBusyY();j+=1){
			this.busyCellsMap[obj.getInitialBusyX()+i][obj.getInitialBusyY()+j]-=1;
		}
	}
	//
	// Update coordinates in kdtree and update object coordinates too
	this.kdtree.updateNodeCoordinates(obj, point);
	//
	// Add object to busyCellsMap using updated coodinates
	for (i=0;i<obj.getSizeBusyX();i+=1){
		for (j=0;j<obj.getSizeBusyY();j+=1){
			this.busyCellsMap[obj.getInitialBusyX()+i][obj.getInitialBusyY()+j]+=1;
		}
	}
}

